package com.hfb.mashibing.alip8.system.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Objects;

/**
 * Socket Client
 * @author HFB
 */
public class T02_BIO_SocketClient {

    private static final String CLIENT_HOST = "127.0.0.1";
    private static final int CLIENT_PORT = 9090;

    public static void main(String[] args) throws IOException {
        while (true) {
            Socket client = new Socket(CLIENT_HOST, CLIENT_PORT);
            client.setSendBufferSize(20); // 20 个字节
            // 推迟发 tcp 包，意味着优化 tcp
            client.setTcpNoDelay(false); // 不推迟发 tcp 包，默认为false
            client.setOOBInline(false); // 是否立即发送数据的第一个字节
            OutputStream out = client.getOutputStream();

            InputStream in = System.in;
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            while (true) {
                String dataLine = reader.readLine();
                if (Objects.nonNull(dataLine)) {
                    System.out.println(dataLine); // 阻塞2
                    for (byte b : dataLine.getBytes()) {
                        out.write(b);
                    }
//                    out.flush();
                }
            }
        }

    }

}
